<?php
/**
 * 归档 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: archives.php 523 2010-06-23 10:06:24Z lisijie86 $
*/

!defined('IN_JBLOG') && exit('Access Denied!');

$cachetime = 86400; //缓存时间：1天

//显示年/月下的文章
if ( $get['date'] ) {
	
	if ( !preg_match('/^[\d\-]+$/', $get['date']) ) {
		error_404();
	}
	
	list($year, $month, $day) = explode('-', $get['date']);
	
	$archives = array();
	
	$page = max(1, intval($get['page']));
	$pagesize = (int)config('pagesize') * 2;
	$offset = ( $page - 1 ) * $pagesize;
	$url = "mod=archives&date={$get['date']}&page={$page}";
	
	//年月日
	if ( $year && $month && $day ) {
		$wheresql = " yearmonth = '{$year}{$month}' AND `day` = '$day'";
	//年月
	} elseif ( $year && $month ) {
		$wheresql = " yearmonth = '{$year}{$month}'";
	//年
	} elseif ( $year ) {
		$wheresql = " yearmonth BETWEEN ".($year * 100)." AND ".(($year+1) * 100);
	} else {
		error_404();
	}
	
	$count = $db->count('calendar', $wheresql);
	
	if ( $count ) {
		
		$postids = array();
		$query = $db->query("SELECT postid FROM ".tname('calendar')." 
		WHERE $wheresql LIMIT $offset, $pagesize");
		while ( $row = $db->fetch_array($query) ) {
			$postids[] = $row['postid'];
		}
		
		if ( $postids ) {
			$query = $db->query("SELECT id,cateid,title,alias,dateline,views,comments FROM ".tname('post')." WHERE 
			id IN (".simplode($postids).") AND `status` = 1 ORDER BY dateline");
			while ( $row = $db->fetch_array($query) ) {
				$cate = $_CACHE['cate'][$row['cateid']];
				$row['url'] = url("mod=post&id={$row['id']}&alias={$row['alias']}");
				$row['category'] = sprintf('<a href="%1$s" title="%2$s">%2$s</a>', url('mod=cate&id='.$cate['id'].'&alias='.$cate['alias']), $cate['catename']);
				$row['posttime'] = get_date($row['dateline']);
				$archives[] = $row;
			}					
		}
		
	}
	
	blog('title',__('文章归档'));
	
//按年月归档
} else {
	
	if ( !$archives = $cache->get('archives') ) {
		$archives = array();
		$query = $db->query("SELECT LEFT(yearmonth,4) AS year, RIGHT(yearmonth, 2) AS month, COUNT(*) AS num FROM ".tname('calendar')." GROUP BY yearmonth ORDER BY yearmonth ASC");
		while ( $row = $db->fetch_array($query) ) {
			$archives[$row['year']][$row['month']] = $row['num'];
		}
		$db->free_result($query);
		@ksort($archives);
		$cache->set('archives', $archives, $cachetime);
	}
	$archives = (array)$archives;
	
	
	blog('title',__('文章归档'));
}

template('archives');
?>